Observables
- class qtealeaves.observables.TNObservables(filename_observables='observables.in', folder_observables='observables', num_trajectories=1, do_write_hdf5=False)[source]
Organization of all the measurements to be taken during a tensor network simulation. To add new observables in the container you should simply use the
+=
operator as shown in the example.Example
obs = TNObservables() obs += any_other_observable
Arguments
- filename_observablesstr
Base filename of the definition with the observables inside the input folder and observables subfolder. A postfix might be appended upon need. The file extension will be chosen by the backend.
- folder_observablesstr
Subfolder for the observable input files inside the input folder.
- num_trajectoriesint
Total number of quantum trajectories.
Details
Up to now, the class organizes and accepts observables of the type
TNObsLocal
,TNObsCorr
,TNDistance2Pure
,TNState2File
,TNObsTensorProduct
,TNObsWeightedSum
,TNObsProjective
,TNObsProbabilities
,TNObsBondEntropy
,TNObsCustom
- add_observable(obj)[source]
Add a specific observable to the measurements. The class of the observable added must match the predefined observables inside this class.
- static add_trajectories(all_results, new)[source]
Add the observables for different quantum trajectories.
Arguments
- all_resultsdict
Dictionary with observables.
- newdict
Dictionary with new observables to add to all_results.
- static avg_trajectories(all_results, num_trajectories)[source]
Get the average of quantum trajectories observables.
Arguments
- all_resultsdict
Dictionary with observables.
- num_trajectoriesint
Total number of quantum trajectories.
- collect_operators()[source]
Collect all operators with some additional information. This function is just collecting the information from all observables stored within this class.
- get_folder_trajectories(folder_name, params)[source]
Evaluate the folder name and add the trajectory id if running trajectories.
Arguments
- folder_namestr
Name of the input/output folder for the simulation.
- paramsdict or list of dicts
The parameter dictionary or dictionaries, which is required to obtain the output folder.
Returns
- folder_namestr
Modified folder name with the trajectory id.
- static get_id_trajectories(val)[source]
Get the id for the given quantum trajectory.
Arguments
- valint
value for id of the quantum trajectory.
- get_num_trajectories(**kwargs)[source]
Get number of quantum trajectories
Arguments
- paramskeyword argument
A dictionary with parameters is accepted as a keyword argument.
- static get_seed_trajectories(params)[source]
Get the seed for the given quantum trajectory.
Arguments
- paramsdict or list of dicts
The parameter dictionary or dictionaries, which is required to obtain the output folder.
Returns
- seedlist
The seed for the simulation has 4 entries. The following rules applies:
entries must be smaller than 4096
entries must be bigger than 0
last entry must be odd
- read(filename, folder, params)[source]
Read all the results and store them in a dictionary.
Arguments
- filenamestr
Filename of the output file (not including the path). This filename can vary for statics and dynamics and therefore has to be passed.
- folderstr
Folder of the output file.
- paramsdict
The parameter dictionary, which is required to obtain the output folder.
- static read_cpu_time_from_log(filename_result, params)[source]
Read the CPU time if it can be resolved via the log file.
Arguments
- filename_resultstr
Filename to the output file including the path. This filename can vary for statics and dynamics and therefore has to be passed. Function assumes that the log-file is stored next to it.
Returns
Iterator returns key, value pair if available.
- read_file(filename, params)[source]
Read all the results from a single file and store them in a dictionary.
Arguments
- filenamestr
Filename to the output file including the path. This filename can vary for statics and dynamics and therefore has to be passed.
- paramsdict
The parameter dictionary, which is required to obtain the output folder.
- write(folder_name, params, operator_map)[source]
Write the information of the observables for fortran as an input file.
Arguments
- folder_namestr
Name of the input folder of the simulation.
- paramsdict
Simulation parameters.
- operator_mapdict
Provides the mapping between the string identifiers for the operators to the integer index in the list of operators.
- write_input(folder_name, params)[source]
(DEPRECATED) Writing input files for input processor 1 and 2.
Arguments
- folder_namestr
Name of the input folder of the simulation.
- paramsdict
Simulation parameters.
- write_results(filename, is_measured, params)[source]
Write the complete measurement file mocking the fortran output. The assumption is that the results buffer of each measurement was set with all the required results.
Arguments
- filenamestr
Target location of the file.
- is_measuredarray-like of bools
Array containing the information about the measurability of a given observable with a given backend
- paramsdict
Simulation parameters.
Local observables
- class qtealeaves.observables.TNObsLocal(name, operator)[source]
The local observable will measure an operator defined on a single site across the complete system. This means that, if the single site has a dimension \(d\) we expect the local observable to be a matrix of dimension \(d\times d\). For example, if we are working with qubits, i.e. \(d=2\), a local observable can be the Pauli matrix \(\sigma_z\).
The local observable will be measured on each site of the tensor network. As such, the output of this measurement will be a dictionary where:
the key is the name of the observable
the value is a list of length \(n\), with \(n\) the number
of sites of the tensor network. The \(i\)-th element of the list will contain the expectation value of the local observable on the \(i\)-th site.
Arguments
- namestr
Define a label under which we can find the observable in the result dictionary.
- operatorstr
Identifier/string for the operator to be measured.
- read(fh, **kwargs)[source]
Read local observables from standard formatted fortran output.
- fhfilehandle
Read the information about the measurements from this filehandle.
- read_hdf5(dataset, params)[source]
Reads the given dataset of observables into a generator. The keys of the dataset are (0-based) integers which correspond to the names of the observables.
Arguments
- dataseth5py dataset object
The dataset to be read out.
- paramsparams dictionary
Unused for now.
Correlation observables
- class qtealeaves.observables.TNObsCorr(name, operators)[source]
The correlation observable measures the correlation between two operators. It cannot be used for fermionic operators which require a Jordan-Wigner transformation. Thus, the correlation is of type
<A_i B_j>
. The indexi
is running over the rows of a matrix, the indexjj
over the columns.( <A_1 B_1> <A_1 B_2> <A_1 B_3> ... ) ( <A_2 B_1> <A_2 B_2> <A_2 B_3> ... ) ( <A_3 B_1> <A_3 B_2> <A_3 B_3> ... ) ( ... ... ... ... )
Arguments
- namestr
Define a label under which we can find the observable in the result dictionary.
- operatorslist of two strings
Identifiers/strings for the operators to be measured.
- read(fh, **kwargs)[source]
Read the measurements of the correlation observable from fortran.
Arguments
- fhfilehandle
Read the information about the measurements from this filehandle.
- read_hdf5(dataset, params)[source]
The data is written into groups, each containing the dataset real, and complex variables also containing a dataset imag. Check if imag exists and sum them up. The names of the groups are (0-based) integers which correspond to the names of the observables.
Arguments
- dataseth5py dataset
The dataset to be read out of.
- paramsparameter dictionary
Unused for now (Dec 2023)
- to_itpo(operators, tensor_backend, num_sites, de_layer=None)[source]
Return an ITPO representing the correlation observable. In the case of the aTTN the function takes care of diagonal terms of corr matrix with the disentanglers on them. These diagonal terms are stored in the order of looping over ii and jj.
Parameters
- operators: TNOperators
The operator class
- tensor_backend: instance of TensorBackend
Tensor backend of the simulation
- num_sites: int
Number of sites of the state
- de_layerDELayer or None, optional
Disentangler layer for which the iTPO layer is created Default to None (standard TN with no disentanglers)
Returns
- ITPO
The ITPO class
- class qtealeaves.observables.TNObsCorr4(name, operators)[source]
Measure the correlation of four operators. This measurement does not do any projections. We skip entries where two or more of the four indices match, e.g., i1 = i2.
Arguments
- namestr
Define a label under which we can find the observable in the result dictionary.
- operatorlist of four strings
Identifiers / strings for the operators to be measured.
Details
Restrictions apply in the case of symmetric tensor, where the measurement might not be available even if it is available without symmetries.
- read(fh, **kwargs)[source]
Read the measurements of the correlation observable from fortran.
Arguments
- fhfilehandle
Read the information about the measurements from this filehandle.
Custom correlation observables
- class qtealeaves.observables.TNObsCustom(name, operators, site_indices, dim=1, mapping='HilbertCurveMap', lattice=None)[source]
The custom observable measures the term of arbitrary size over the arbitrary positions. Thus, the observable is of type
<A_i B_j ... C_k>
. The results are stored in 1D array, with the order as provided in input. All operators in the measured n-body term must be placed on different sites, i != j != … != k”.If the system is 2d or 3d, user can provide the positions of measurements either in the already flattened, i.e. 1d indexing, or as 2d/3d indexing. In the latter case, additional arguments (see below) must be provided.
Arguments
- namestr
Define a label under which we can find the observable in the result dictionary.
- operatorslist (of length term_size) of strings
Identifiers/strings for the operators to be measured.
- site_indiceslist of lists
On which sites we want to measure specified operators. E.g. if we want to measure 2-body correlators on sites [1,2] and [3,4], site_indices=[[1,2],[3,4]]. REMARK: counting starts at 0.
If working with 2d/3d systems:
- dim1, 2, or 3, optional
Dimensionality of the lattice (1d, 2d, 3d) Default is 1.
- mappingstring or instance of
HilbertCurveMap
, optional If dim != 1, which 2d/3d to 1d mapping to use. Possible inputs are: ‘HilbertCurveMap’, ‘SnakeMap’, and ‘ZigZagMap’. Default is ‘HilbertCurveMap’.
- latticelist, optional
If working with 2d or 3d systems, a lattice size must be given to compute the corresponding mapping to 1d.
- collect_operators()[source]
Documentation see
_TNObsBase.collect_operators()
.In the case of n-body operators with n>2, we choose that the bulk operators have label ‘r’. However, note that this has limitations if the symmetry number changes.
- get_sites_1d(site_indices, dim, lattice, mapping)[source]
In the case of 2D, or 3D input of the measurement position sites, give back the flattened (mapped to 1d) array for measurement position sites.
Parameters
- site_indiceslist of measurement positions
On which sites we want to measure specified operators. REMARK: counting starts at 0.
- dim2 or 3
Dimensionality of the lattice (2d, 3d)
- latticelist, optional
Lattice size.
- mappingstring or instance of
HilbertCurveMap
If dim != 1, which 2d/3d to 1d mapping to use. Possible inputs are: ‘HilbertCurveMap’, ‘SnakeMap’, and ‘ZigZagMap’.
- read(fh, **kwargs)[source]
Read the measurements of the correlation observable from fortran.
Arguments
- fhfilehandle
Read the information about the measurements from this filehandle.
- to_itpo(operators, tensor_backend, num_sites)[source]
Return an ITPO representing the custom correlation observable. Since custom corr don’t handle diagonal terms, the function is same for TTN and aTTN.
Parameters
- operators: TNOperators
The operator class
- tensor_backend: instance of TensorBackend
Tensor backend of the simulation
- num_sites: int
Number of sites of the state
Returns
- ITPO
The ITPO class
Time correlators
- class qtealeaves.observables.TNObsTZeroCorr(name, operators, site_idx)[source]
Arguments
- namestr
Define a label under which we can finde the observable in the result dictionary.
- operatorlist of two strings
Identifiers/strings for the operators to be measured. The first operator is applied at t=0, the second at all t during measurements of the time evolution.
- site_idxint
Specify on which site the first operator should be measured on.
- read(fh, **kwargs)[source]
Read the measurements of the time correlator obsverable from fortran.
Arguments
- fhfilehandle
Read the information about the measurements from this filehandle.
Tensor product
- class qtealeaves.observables.TNObsTensorProduct(name, operators, sites)[source]
Observables which are tensor product between one-site or two-site operators.
This observable enables the computation of observables of the following form. On a tensor network with \(n\) sites we can measure \(O\) of the form:
\[O = o_0 \otimes o_2 \otimes o_3 \otimes \dots \otimes o_{n-1}\]where the different local observables \(o_i\) might be different or even be the identity.
The output of the measurement will be a dictionary where:
The key is the name of the observable
The value is its expectation value
An example of such an observable is the Parity of the system. If we work on a system of qubits, then to measure the parity we simply have to use \(o_i=o_j=\sigma_z \; \forall \; i,j\in\{0, n-1\}\), where \(\sigma_z\) is the Pauli matrix.
Parameters
- name: str
Name to identify the observable
- operators: list of str or str
Idenitifiers/names for the operators to be measured. If str the same operator is applied to the whole MPS
- sites: list of int or int
Indexes to which the operators should be applied, in the same order. If int instead it is the size of the chain, and the operator is assumed to be applied to each site of the tensor network
- read(fh, **kwargs)[source]
Read the measurements of the correlation observable from fortran.
Parameters
- fhfilehandle
Read the information about the measurements from this filehandle.
Weighted sum of tensor products
- class qtealeaves.observables.TNObsWeightedSum(name, tp_operators, coeffs, use_itpo=False)[source]
Class to measure observables which is the weighted sum of tensor product, which means of the type
\[O = \sum_{i=0}^m \alpha_i\left( o_1^i\otimes o_2^i \otimes \dots \otimes o_n^i \right)\]where \(m\) is the number of addends and \(n\) the number of sites. For further informations about the single observable \(O_i=o_1^i\otimes o_2^i \otimes \dots \otimes o_n^i\) see the documentation of
TNObsTensorProduct
.The output of the measurement will be a dictionary where:
The key is the name of the observable
The value is its expectation value
An example of this observable are Pauli decompositions of Hamiltonian, i.e. Hamiltonians written as a weighted sum of tensor product operators formed by Pauli matrices. They are usually used in the Quantum chemistry applications, such as the Variational Quantum Eigensolver.
Parameters
- name: str
Name to identify the observable
- tp_operators:
TNObsTensorProduct
Tensor product observables. Its length, i.e. the number of tensor product observables contained in it, should be the same of the number of complex coefficients.
- coeffs: list of complex
Coefficients of the weighted sum for each tp_operators
- use_itpo: bool, optional
If True, measure using ITPO. Default to False. Consumed in python.
- classmethod from_pauli_string(name, pauli_string, use_itpo=False)[source]
Initialize the observable from a qiskit chemistry pauli string format. First, outside of the function use the WeightedPauliOperator method to_dict() and then give that dict as input to this function
Parameters
- name: str
Name of the observable
- pauli_string: dict
Dictionary of pauli strings
- use_itpo: bool, optional
If True, measure using ITPO. Default to False. Consumed in python.
Returns
- TNObsWeightedSum
The weighted sum observable initialized from the pauli dictionary
- read(fh, **kwargs)[source]
Read the measurements of the correlation observable from fortran.
Parameters
- fhfilehandle
Read the information about the measurements from this filehandle.
- to_itpo(operators, tensor_backend, num_sites)[source]
Return an ITPO represented the weighted sum observable
Parameters
- operators: TNOperators
The operator class
- tensor_backend: instance of TensorBackend
Tensor backend of the simulation
- num_sites: int
Number of sites in the state to be measures
Returns
- ITPO
The ITPO class
Bond entropy
- class qtealeaves.observables.TNObsBondEntropy[source]
Observable to enable the measurement of the Von Neumann bond entropy at the end of a circuit. If the state is pure, than this measurement is equal to the entanglement. Otherwise it is not well defined. Given a quantum state of \(n\) sites \(|\psi\rangle\) the Von Neumann entropy of the bipartition \(A(B)\) with \(n_{A(B)}\) sites is defined as:
\[S_V(\rho_A) = -\mathrm{Tr} \rho_A\ln(\rho_A), \quad \rho_A=\mathrm{Tr}_B\left( |\psi\rangle\langle\psi|\right)\]This value should be computed using the natural logarithm, i.e. the logarithm in base \(e\).
The output of the measurement will be a dictionary, where:
As keys, we report on continous range of site which form the first bipartition. For example, the continuous range (4, 5) has the bipartitions [4, 5] vs [0, 1, 2, 3, 6, 7]. An MPS will define the first bipartitions in the different cuts as (0, 0), (0, 1), (0, 2), (0, 3), etc.
Indices are python indices starting at zero in the keys.
As value the result of \(S_V\). Natural log is used for both MPS and TTN.
The expression above for the computation of the bond entropy is quite complex. Using tensor network we can strongly simplify it, using the singular values \(s_i\) “stored” in the link. This is equivalent to look at the eigenvalues \(\lambda_i\) of the reduced density matrix \(\rho_A\) for a pure system like MPS and TTN:
\[S_V(\rho_A) = -\sum_{i} \lambda_i \ln(\lambda_i) = -\sum_{i} s_i^2 \ln(s_i^2)\]- read(fh, **kwargs)[source]
Read the measurements of the projective measurement observable from fortran.
Parameters
- fhfilehandle
Read the information about the measurements from this filehandle.
Distance to pure states
- class qtealeaves.observables.TNDistance2Pure(name, path_to_state)[source]
Distance observable will measure the distance of the quantum system to one or more pure states defined within this observable as filenames. We measure the overlap and return a complex number \(\rangle\phi | \psi\langle\).
Arguments
- namestr
Define a label under which we can find the observable in the result dictionary.
- path_to_statestr
Filename to the state. The default extension for formatted Fortran TTNs is
.ttn
and for unformatted Fortran TTNs is.ttnbin
. Other file extension might be added.
- static check_extension(path_to_state)[source]
Check that the file uses a valid file extension at least readable by some simulation.
- read(fh, **kwargs)[source]
Read distance observables from standard formatted fortran output.
- fhfilehandle
Read the information about the measurements from this filehandle.
Probabilities of projective measurements via tree
- class qtealeaves.observables.TNObsProbabilities(prob_type='U', num_samples=100, prob_threshold=0.9, qiskit_convention=False)[source]
Observable to measure the probabilities of the state configurations at the end of an evolution. The probabilities are computed following a probability tree, where each node is a site, and has a number of childs equal to the local dimension \(d\) of the site. We keep track of the probabilities of the paths from the root to the leaves. The leaves identify the final state. For example, a state written as
\[|\psi\rangle = \sqrt{N}\left(|00\rangle + |01\rangle + 2|11\rangle\right)\]with \(N=\frac{1}{6}\) will have the following probability tree. Branches going left measures \(0\) while branches on the right measures \(1\). The ordering here is the right-most site being the index-0 site.
----o---- # No measure, state s2,s1 p=1/6/ \p=5/6 # First measure, states s2,0 or s2,1 o o p=1/6/ \p=0 p=1/6/ \p=4/6 # Second measure, states 0,0 or 0,1 or 1,1 00 10 01 11
There are three possible ways of computing the probability:
Going down evenly on the tree, which means following ALL possible paths at the same time, and discarding paths which probability is below an input threshold \(\epsilon\). You might have no outputs, if all the branches has a probability \(p<\epsilon\).
Going down greedily on the tree, which means following each time the path with highest probability, until the total probability measured is more then a threshold \(\mathcal{E}\). This procedure is dangerous, since it can take an exponentially-long time if \(\mathcal{E}\) is too high.
Going down unbiasedly on the tree, which means drawing a
num_sumples
uniformly distributed random numbers \(u\sim U(0,1)\) and ending in the leaf which probability interval \([p_{\mathrm{low}}, p_{\mathrm{high}}]\) is such that \(u\in [p_{\mathrm{low}}, p_{\mathrm{high}}]\). This is the suggested method. See http://arxiv.org/abs/2401.10330 for additional details.
The result of the observable will be a dictionary where:
the keys are the measured state on a given basis
the values are the probabilities of measuring the key for the even and greedy approach, while they are the probability intervals for the unbiased approach.
Parameters
- prob_type: str, optional
The type of probability measure. Default to ‘U’. Available: - ‘U’, unbiased - ‘G’, greedy - ‘E’, even. Also implemented in Fortran backend
- num_samples: int, optional
Number of samples for the unbiased prob_type. Default to 100. If a list is passed, the function is called multiple times with that list of parameters.
- prob_threshold: float, optional
probability treshold for prob_type=(‘G’, ‘E’). Default to 0.9.
- qiskit_conventionbool, optional
If you should use the qiskit convention when measuring, i.e. least significant qubit on the right. Default to False.
- read(fh, **kwargs)[source]
Read the measurements of the projective measurement observable from fortran.
Parameters
- fhfilehandle
Read the information about the measurements from this filehandle.
Probabilities of projective measurements via intervals
- class qtealeaves.observables.TNObsProjective(num_shots, qiskit_convention=False)[source]
Observable to enable the final projective measurements after the evolution. This observable is meant to give single-shot measurements: the system is projectively measured a number of times equal to num_shots, such that the user can observe a statistic of the distribution of the state.
The result of the observable will be a dictionary where:
the keys are the measured state on a given basis
the values are the number of occurrences of the keys in the num_shots single shots measurements
As an example, if we work with qubits, we measure on the computational base and we end up with the state \(\frac{1}{\sqrt{2}}(|00\rangle+|11\rangle)\), requesting 1000 num_shots we will end up with the following result:
{'00' : 505, '11' : 495}
. Take into account that the measurement is probabilistic and such is will only be an approximation of the true probability distribution, that in the example case would be \(p_{00}=p_{11}=0.5\).Parameters
- num_shotsint
Number of projective measurements
- qiskit_conventionbool, optional
If you should use the qiskit convention when measuring, i.e. least significant qubit on the right. Default to False.
- avg_trajectories(all_results, num_trajectories)[source]
Documentation see
_TNObsBase.avg_trajectories()
.
- read(fh, **kwargs)[source]
Read the measurements of the projective measurement observable from fortran.
Parameters
- fhfilehandle
Read the information about the measurements from this filehandle.
Saving states as a file
- class qtealeaves.observables.TNState2File(name, formatting)[source]
Write the state to a file.
We stress that saving the state to a file will enable to further measure observables, since you will have available all the informations you had at the end of the simulation.
Warning
While saving the state can be useful, it can really slow down the evolution when it is saved at each time-step of a time evolution. Please use this observable carefully! Reference to the description on the backend for more specific informations.
Arguments
- namestr
Filename to save the state.
- formattingchar
Specifies format, i.e., ‘F’ for formatted, ‘U’ for unformatted, or ‘D’ for formatted without symmetries. On the python backend, U is pickled, F is formatted D is converted to dense tensor and pickled (especially the last on is different from fortran, where the dense TN is stored as formatted file).
- add_trajectories(all_results, new)[source]
Documentation see
_TNObsBase.add_trajectories()
. Here, we generate a list of filenames.
- avg_trajectories(all_results, num_trajectories)[source]
Documentation see
_TNObsBase.avg_trajectories()
. Here, we return the list of filenames as is, no action possible for averaging.
- read(fh, **kwargs)[source]
Read file observable from standard formatted fortran output.
Arguments
- fhfilehandle
Read the information about the measurements from this filehandle.
- paramsdict (in kwargs)
The parameter dictionary, which is required to obtain the output folder. It is required to evaluate callable etc. used in
self.name
.
Abstract observables
- class qtealeaves.observables.tnobase._TNObsBase(name, *args, **kwargs)[source]
Abstract base class for observables.
Attributes
- name: str
Name to identify the observable
- results_bufferdict
Store the results of the measurement of the observable
- is_measuredbool
Flag known by the backend, if True the observable can be measured by the backend, otherwise it can’t be measured.
- add_trajectories(all_results, new)[source]
Add the observables for different quantum trajectories.
Arguments
- all_resultsdict
Dictionary with observables.
- newdict
Dictionary with new observables to add to all_results.
- avg_trajectories(all_results, num_trajectories)[source]
Get the average of quantum trajectories observables.
Arguments
- all_resultsdict
Dictionary with observables.
- num_trajectoriesint
Total number of quantum trajectories.
- collect_operators()[source]
Observables which require operators must provide this method, because operators with symmetries might not be written otherwise.
Details
The problems are, for example, correlations with equal operators because they cannot be contracted over their third link.
- get_id()[source]
Get the address in memory, which is useful instead of hashing the complete object or for comparisons.
- read(fh, **kwargs)[source]
The measurement outcomes are written by fortran and we read them within this method. If the format how the measurements are written changes on the fortran side, this method must be adapted.
- read_hdf5(dataset, params)[source]
Documentation see
_TNObsBase.read_hdf5()
.Arguments
- dataseth5py dataset
The dataset to be read out of.
- paramsparameter dictionary
Unused for now (Dec 2023)
- write(fh, **kwargs)[source]
Write the information about the measurements to a file, which is later on read by fortran. The corresponding fortran methods have to changed if the write methods are changed.
- write_input_v1(folder_name, params)[source]
(Deprecated) Empty iterator to comply with old input file. Specific observables which exist in the v1 of the input processor might overwrite this method:
Arguments
- folder_namestr
Name where to write measurements
- paramsdict
Dictionary with the simulations parameters.
- write_results(fh, is_measured, **kwargs)[source]
Write the actual results to a file mocking the fortran output. Therefore, the results have to be stored in the result buffer.
Arguments
- fhfilehandle
Open filehandle where the results are written to.
- is_measuredbool
If True, the backend can measure the observable